package com.ttt.servicer.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ttt.mapper.UserMapper;
import com.ttt.pojo.User;
import com.ttt.servicer.UserService;
import com.ttt.util.Result;
import com.ttt.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {



    @Autowired
    private UserMapper userMapper;


    private Result result;

    @Override
    public Result findUserLogin(User user) {



        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //构建查询语句
        //查询字段名为username的用户
        queryWrapper.eq("phone",user.getPhone());
        //执行查询
        User selectOne = userMapper.selectOne(queryWrapper);

        //如果用户名密码都为空
        if (selectOne == null){
            result = Result.build("账号未注册！",ResultCodeEnum.NOTLOGIN);
        }else {

            //如果账号等于null，用户不存在
            if (selectOne.getPhone() == null){
                //用户名不存在
                result = Result.build("用户名不存在", ResultCodeEnum.USERNAME_ERROR);
            }

            //如果查询到的密码和用户名的密码不相同，则密码错误
            if ( !selectOne.getPassword().equals(user.getPassword())){
                result = Result.build("密码错误", ResultCodeEnum.PASSWORD_ERROR);
            }

            //如果用户名密码和数据库里面的一样
            if (selectOne.getPhone().equals(user.getPhone()) && selectOne.getPassword().equals(user.getPassword())){
                result = Result.build("ok",ResultCodeEnum.SUCCESS);
            }


        }
        return result;
    }

    @Override
    public Result register(User user) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",user.getPhone());
        User selectOne = userMapper.selectOne(queryWrapper);

        //判断用户是否已经存在
        if (selectOne != null){
            result = Result.build("账号已经存在",ResultCodeEnum.PHONE_USED);
        }else {
            //将用户信息进行注册
            int insert = userMapper.insert(user);

            result = Result.build("注册成功！",ResultCodeEnum.SUCCESS);

        }

        return result;
    }
}
